package com.atmilan.quartz.utils.product;

import java.util.List;
import java.util.stream.Collectors;

import com.atmilan.quartz.model.entity.buyer.Supplier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.atmilan.quartz.utils.unibuy.client.OpenClient;
import com.atmilan.quartz.utils.unibuy.common.RequestMethod;
import com.atmilan.quartz.utils.unibuy.model.CommonQueryModel;
import com.atmilan.quartz.utils.unibuy.model.goods.GoodsQueryModel;
import com.atmilan.quartz.utils.unibuy.model.goods.PriceQueryModel;
import com.atmilan.quartz.utils.unibuy.model.goods.StockQueryModel;
import com.atmilan.quartz.utils.unibuy.request.goods.GoodsQueryRequest;
import com.atmilan.quartz.utils.unibuy.request.goods.PriceQueryRequest;
import com.atmilan.quartz.utils.unibuy.request.goods.StockQueryRequest;
import com.atmilan.quartz.utils.unibuy.response.goods.GoodsQueryResponse;
import com.atmilan.quartz.utils.unibuy.response.goods.PriceQueryResponse;
import com.atmilan.quartz.utils.unibuy.response.goods.StockQueryResponse;
import com.atmilan.quartz.utils.unibuy.vo.CommonPageVO;
import com.atmilan.quartz.utils.unibuy.vo.goods.GoodsVO;
import com.atmilan.quartz.utils.unibuy.vo.goods.PriceVO;
import com.atmilan.quartz.utils.unibuy.vo.goods.StockVO;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class UnibuyProductUtil {

    @Value("${unibuy.url}")
    private String unibuyUrl;
//    @Value("${unibuy.appId}")
//    private String unibuyAppId;
//    @Value("${unibuy.privateKey}")
//    private String unibuyPrivateKey;
//    @Value("${unibuy.publicKey}")
//    private String unibuyPublicKey;

    public List<GoodsVO> selectUnibuyPage(Supplier supplier, int pageNo, CommonQueryModel commonQueryModel, String startTime, String endTime) throws Exception {
        GoodsQueryModel model = new GoodsQueryModel();
        model.setStartTime(startTime);
        model.setEndTime(endTime);
        model.setPageNo(pageNo);
        model.setChannelNo(supplier.getUnibuyChannelno());

        //封装查询参数
        GoodsQueryRequest request = new GoodsQueryRequest();
        request.setBizModel(model);
        request.setRequestMethod(RequestMethod.POST);

        // 发送请求
        OpenClient client = new OpenClient(unibuyUrl, supplier.getUnibuyAppid(), supplier.getUnibuyPrivatekey(), supplier.getUnibuyPublickey());
        final GoodsQueryResponse response = client.execute(request);
        if (response.isSuccess()) {
            final CommonPageVO<GoodsVO> content = response.getContent();
            final List<GoodsVO> goodsVOs = content.getList();
            commonQueryModel.setMaxPage(1);
            if (null != content.getTotal() && content.getTotal() > model.getPageSize()){
                Integer total = content.getTotal();
                int num = content.getTotal() / model.getPageSize();
                if (total%model.getPageSize()!=0){
                    num++;
                }
                commonQueryModel.setMaxPage(num);
            }
            if(CollectionUtils.isEmpty(goodsVOs)) {
                return goodsVOs;
            }

            List<String> skuNos = goodsVOs.stream().map(GoodsVO :: getSkuNo).collect(Collectors.toList());
            List<PriceVO> prices = selectUnibuyPrice(supplier.getUnibuyChannelno(), skuNos, client);
            List<StockVO> stocks = selectUnibuyStock(supplier.getUnibuyChannelno(), skuNos, client);
            for(GoodsVO goods : goodsVOs) {
                for(PriceVO price : prices) {
                    // 下次接收的人希望把上面list改成map，谁没事在这里傻循环匹配，不想改了
                    if(goods.getSkuNo().equals(price.getSkuNo())) {
                        goods.setCostPrice(price.getCostPrice());
                        goods.setMarketPrice(price.getMarketPrice());
                        goods.setSeaMarketPrice(price.getSeaMarketPrice());
                        goods.setSeaMarketPriceUnit(price.getSeaMarketPriceUnit());
                        goods.setTaxesFee(price.getTaxesFee());
                        goods.setFreightFee(price.getFreightFee());
                    }
                }
                for(StockVO stock : stocks) {
                    if(goods.getSkuNo().equals(stock.getSkuNo())) {
                        goods.setQuantity(stock.getQuantity());
                    }
                }
            }

            return goodsVOs;
        } else {
            log.info("--------------- unibuy 返回结果: {}", JSON.toJSONString(response));
        }

        return null;
    }

    // 查询商品价格
    private List<PriceVO> selectUnibuyPrice(String unibuyChannelNo, List<String> skuNos, OpenClient client) {
        // 请求参数
        PriceQueryModel model = new PriceQueryModel();
        model.setChannelNo(unibuyChannelNo);
        model.setSkuNos(skuNos);
        PriceQueryRequest request = new PriceQueryRequest();
        request.setBizModel(model);
        request.setRequestMethod(RequestMethod.POST);

        // 发送请求
        final PriceQueryResponse response = client.execute(request);

        if(!response.isSuccess()) {
            return null;
        }
        final CommonPageVO<PriceVO> content = response.getContent();
        final List<PriceVO> list = content.getList();

        return list;
    }

    // 商品库存查询
    private List<StockVO> selectUnibuyStock(String unibuyChannelNo, List<String> skuNos, OpenClient client) {
        // 请求参数
        StockQueryModel model = new StockQueryModel();
        model.setChannelNo(unibuyChannelNo);
        model.setSkuNos(skuNos);
        StockQueryRequest request = new StockQueryRequest();
        request.setBizModel(model);
        request.setRequestMethod(RequestMethod.POST);

        StockQueryResponse response = client.execute(request);
        if (response.isSuccess() && response.getContent() != null) {
            CommonPageVO<StockVO> content = response.getContent();
            List<StockVO> list = content.getList();
            return list;
        }

        return null;
    }

    public static void main(String[] args) {
//        String url = "http://sop-gateway.opechk.com";
//        String id = "202303091083338187440390144";
//        String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/li2TuR+Gx3Z1\n" +
//                "OVP0WBrqg3iklbiNuqNEf8dDw3Zkg82eZwVQg7BUu2NWqU5iNTs9MhtxKXGgLtyV\n" +
//                "hkDfxNDQ1EDU5lEiRppTzpj79a4YS0dfiOVoQATVu+pCeBuWPdehpBw8yJmUeTRG\n" +
//                "KexjqT0iSlTH3Om7pB+rPSVedoqt038zmmYw40eZq6BTA6e5dblkfTuoyxgRB3LV\n" +
//                "aGYYEBCYriCcb7t2/wx/yblDN2ckWlw8QFBJu5ymPLoNwdUnBjWiqUYQs3WZpFtt\n" +
//                "vrbP0CEg+a46viZzkeOa324d9YAI7F902IrxFJ5uUCDe97bwR+WM8lNOhObLGAKb\n" +
//                "eqO7cD+lAgMBAAECggEAbGiySZDLQhzD7vkNhIoGUQUr0xXVZH1jvXMAclu8NoxO\n" +
//                "YX+yBik+MfQG9ha/f9rXNn2QAayN2zIpJ4LcWsKn1kMEnHPnHRoOYbXZ41jVtnGC\n" +
//                "ZZC1HxR6p+a5W/tSwOUlixWt1Mc+AEHFTp6SYKJ3MVwWNTHQIJlyQhdLefRh7JFx\n" +
//                "MD0gsHKy6h4er2c/gE1h/1BtpSfVRMFZucnpvrdS8az6sE8Dcsie/129Fy2S7kR0\n" +
//                "joEDAvMWqrsz9fLKnQYClbe1TDIF0MhnrerA95Xbgtwlejxm+dLLw3pJEgBXOXmc\n" +
//                "pVD3xQVHNskimpDOJ9gqJCyv5JUjYZY5DcJtqssAgQKBgQDxOSxRc/3yMC3OS3U2\n" +
//                "QaX1sInnv0uR2TnyMl4xhQcR0KQ28aZj+lXS42sejunHVKvPosr27UIVIzo5DEBj\n" +
//                "qDkf7Hvp6hFQfDcbCOyw6yKX+95jSg78BzWfrw/DA7jdC+nPDDw8tplK9xqiGIHx\n" +
//                "lgiB2JSlK/klL/Od0C+Mo/wVyQKBgQDLUpwiEGbXy4KsvdD/gyeHwBVeM2hsUByY\n" +
//                "uKnPyFkzEtCyNhwgjWTe3+fklyAhkNbDCCXlYw9KgIoQqxXqHDDaba1hbPflpBR4\n" +
//                "/AMne2zfUfPU2cCi6TbPp57fWCKsCGiNRKW20A3Ww9Uk14BXedk1LKDq2N4LELwb\n" +
//                "3kts7pT4/QKBgCsEPhH8dFHHI7QBItLdHCJXLBCGvYwxx7KYJtH/3gXgRhiCOWDk\n" +
//                "2H82DPkzFR91yvnJFxa3sqwgTxazR5w9+Inn2yUYl6PZst4AVm0qUU33HW5pW4i4\n" +
//                "JGjoiBAHzuSkZjqE/Qz6pxWGQVqcsjeJwNSe8csOr2xhQ7ll0cTrzV15AoGAVffB\n" +
//                "6G1C7q8vu1YuzjpoNm+zGTdnSZS94p0Bv8cYYA3ui8txLRpbshi99dsoTMju5VvG\n" +
//                "miy+RGQA/Hc6Nthgl5qUGoN2dXRg656yvrjjGbGPBUpktv0gncBj3k9nqZGMk16Z\n" +
//                "KqjhkRMQRhmQPGxauK78AxBbIhabUrU08wQVnQkCgYEA1N908zm55WF+8T9dyWZt\n" +
//                "lykQEbRKe+fGxj3u6aCA970tN11v6octyMu6mRvrmIRXNXGd8TqvK/o0aZwDN5Dk\n" +
//                "2dEPDD2FmXQIMEtY0lm1byXtFLRCBAhG83c6kY5iM0V4iWzWtyTPgTvVTYSyAPCt\n" +
//                "r5Slz01e43Bcxyo5egQHh/I=";
//        String publickey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsCdp+OF3eN5FjM8UHles593x0adlCsIwsPOWiuK4i4cvmd4sTt+C5HwTi8g3uDU1lSFSaXAtTOkIBwvn8+7PEqqSsLJkh0rIN5MjVFbZCe6C+cW6dhuhT6NsNgmhdmuT5rNvKqrE6wJFE0Tp2XhXDePj6MUFf7Oimp3XLZo+U8XkZYPqCqSops23wCE38IwQsmOEUk/Z2kDJChgaAtUtpadnBbApT6LCJ7ypS4QKR7QDaO9LCd2Uq73zM0HA8hxuuvUYBSmdcu8Bprdp99gOTVKn93+quzvUzdY0rUwEW6PT1jzHn1D4kY+gBiNPCJdgqhBm2RiCSCdThM0iAyTCWwIDAQAB";
//
//        System.out.println(Math.ceil(250.0/100.0));

        GoodsQueryModel model = new GoodsQueryModel();
        //yyyy-MM-dd HH:mm:ss
        model.setStartTime("2023-11-23 05:33:00");
        model.setEndTime("2023-11-23 10:33:00");
        model.setPageNo(1);
        model.setChannelNo("3426");

        //封装查询参数
        GoodsQueryRequest request = new GoodsQueryRequest();
        request.setBizModel(model);
        request.setRequestMethod(RequestMethod.POST);

        // 发送请求
        OpenClient client = new OpenClient("http://sop-gateway.opechk.com", "202303091083338187440390144", "r5Slz01e43Bcxyo5egQHh/I=", "+gBiNPCJdgqhBm2RiCSCdThM0iAyTCWwIDAQAB");
        final GoodsQueryResponse response = client.execute(request);
        System.out.println();
    }

}
